package com.blast.manager.delay.ui

import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.KeyEvent
import android.widget.AdapterView
import com.alibaba.fastjson.JSONObject
import com.blast.manager.R
import com.blast.manager.bean.OnlineJsonBean
import com.blast.manager.delay.presenter.ShowDelayDataPresenter
import com.blast.manager.uitl.ManagerHttpUtil
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.HttpParams
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.PostRequest
import com.wxl.common.AppConstant
import com.wxl.common.AppContext
import com.wxl.common.base.AbsActivity
import com.wxl.common.event.RefreshDataEvent
import com.wxl.common.http.CommonHttpUtil
import com.wxl.common.http.OkGoApi
import com.wxl.common.http.SerialHttpCallback
import com.wxl.common.life.LifecycleManager
import com.wxl.common.life.ViewModelQuick
import com.wxl.common.room.entity.*
import com.wxl.common.room.helper.DBHelper
import com.wxl.common.util.*
import com.wxl.common.wiget.SkinKeyEventEditorText
import com.wxl.common.wiget.TipPop
import io.reactivex.ObservableOnSubscribe
import io.reactivex.functions.Action
import kotlinx.android.synthetic.main.activity_online_auth_layout.*

class OnlineAuthActivity : AbsActivity() {

    companion object {
        fun start(context: Context, data:ArrayList<LeiGuanEntity>){
            val intent = Intent(context, OnlineAuthActivity::class.java)
            AppContext.appContext.setLeiGuanEntity("OnlineAuthData",data)
            intent.putExtra("key", "OnlineAuthData")
            context.startActivity(intent)
        }
    }

    private var porjectName: String? = null

    private var loadDialog: BasePopupView? = null

    private lateinit var mNoAuthorizeList: ArrayList<LeiGuanEntity>

    private val keyEtViews = arrayListOf<SkinKeyEventEditorText>()

    private var mCurrentEtFocusPosition = 0

    override fun getCreateContentViewId(): Int {
        return R.layout.activity_online_auth_layout
    }

    override fun onCreateViewChanged() {
        isCheckAppUpgrade = false
        setTopTitle("在线授权")

        mNoAuthorizeList = AppContext.appContext.getLeiGuanEntity(intent.getStringExtra("key")!!)

        CommonHttpUtil.getDetonatorInfo(object :
            ObservableUtil.Companion.OnNextCallback<DetonatorEntity>() {
            override fun onNext(t: DetonatorEntity) {
                onlineAuthDmName.text = t.buydeptid
                onlineAuthDmCode.text = t.buydept
                onlineAuthQbqCode.text = t.num
                if (!AppConstant.isTest) {
                    setNetHTView(t.buydept)
                }
            }

            override fun error(e: Throwable) {
                getDbContractData()
            }
        })


        onlineAuthBack.setOnClickListener {
            addLog("返回", "取消在线授权")
            finish()
        }

        onlineAuthSure.setOnClickListener {
            addLog("确定", "提交在线授权")
            submit()
        }

        if (AppConstant.isTest) {
            onlineAuthHtCode.setText("370101318060004")
            onlineAuthXmCode.setText("370100X15040025")
            onlineAuthHtName.setText("华丰测试合同")
        }

        keyEtViews.add(onlineAuthHtCode)
        keyEtViews.add(onlineAuthXmCode)
        keyEtViews.add(onlineAuthHtName)

        onEditorKeyEnterDownEvent()
    }

    /**
     * 输入框按下确定键
     */
    private fun onEditorKeyEnterDownEvent() {
        keyEtViews[mCurrentEtFocusPosition].requestFocus()
        for ((i, v) in keyEtViews.withIndex()) {
            v.setOnKeyDownEventCallback(object :
                SkinKeyEventEditorText.Companion.OnKeyDownEventCallback {
                override fun onKeyDownEvent(keyCode: Int, event: KeyEvent?): Boolean {
                    if (keyCode == KeyEvent.KEYCODE_ENTER) {
                        return this@OnlineAuthActivity.onKeyDown(keyCode, event)
                    }
                    return false
                }
            })
            v.setOnFocusChangeListener { v, hasFocus ->
                if (hasFocus) {
                    mCurrentEtFocusPosition = i
                }
            }
        }
    }


    override fun onKeyDownEvent(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_ENTER) {
            mCurrentEtFocusPosition++
            if (mCurrentEtFocusPosition < keyEtViews.size) {
                keyEtViews[mCurrentEtFocusPosition].requestFocus()
                return true
            }
        }
        if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_F4) {
            onlineAuthSure.performClick()
        }
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_F1) {
            onlineAuthBack.performClick()
        }
        return true
    }

    private fun submit() {
        if (TextUtils.isEmpty(onlineAuthHtCode.text)) {
            Toll.toll("合同编号不能为空。")
            return
        }
        if (TextUtils.isEmpty(onlineAuthXmCode.text)) {
            Toll.toll("项目编号不能为空。")
            return
        }
        if (TextUtils.isEmpty(onlineAuthHtName.text)) {
            Toll.toll("合同名称不能为空。")
            return
        }

        loadDialog = XPopup.Builder(this)
            .dismissOnTouchOutside(false)
            .dismissOnBackPressed(false)
            .asLoading("正在提交授权...")
            .show()

        addPop(loadDialog as BasePopupView)

        if (AppConstant.isTest) {
            loadTest()
        } else {
            load()
        }

    }


    private fun load() {
        val mOnlineJsonBean = OnlineJsonBean()
        mOnlineJsonBean.dwdm = onlineAuthDmCode.text.toString()
        mOnlineJsonBean.htid = onlineAuthHtCode.text.toString()
        mOnlineJsonBean.jd = AppContext.appContext.getLon().toString()
        mOnlineJsonBean.wd = AppContext.appContext.getLat().toString()
        mOnlineJsonBean.sbbh = onlineAuthQbqCode.text.toString()
        mOnlineJsonBean.xmbh = onlineAuthXmCode.text.toString()
        val uids = StringBuffer()
        mNoAuthorizeList.forEach {
            uids.append(it.UID + ",")
        }
        if (!TextUtils.isEmpty(uids)) {
            uids.deleteCharAt(uids.length - 1)
        }
        mOnlineJsonBean.uid = uids.toString()
        load(mOnlineJsonBean)
    }

    private fun loadTest() {
        val mOnlineJsonBean = OnlineJsonBean()
        mOnlineJsonBean.uid = "6070309507000,0070101900181,6100101D99850"
        mOnlineJsonBean.dwdm = "3701004200003"
        mOnlineJsonBean.htid = "370101318060004"
        mOnlineJsonBean.xmbh = "370100X15040025"
        mOnlineJsonBean.sbbh = "F90000000000"
        mOnlineJsonBean.jd = "114.065"
        mOnlineJsonBean.wd = "22.511"
        load(mOnlineJsonBean)
    }

    private fun load(mOnlineJsonBean: OnlineJsonBean) {
        val url =
            EncryptUtils.endocdeNoURL(JSONObject.toJSONString(mOnlineJsonBean), EncryptUtils.mbolsk)
        OkGoApi.api.setBaseUrl(AppConstant.mbBaseUrl + "DzlgMmxzJsonServlert", application)
        val param = HttpParams("param", url)
        val request = OkGoApi.api.post() as PostRequest<String>
        request.params(param)
        request.execute(object : StringCallback() {
            override fun onSuccess(response: Response<String>?) {
                if (response != null && response.isSuccessful && response.body() != null) {
                    val content = EncryptUtils.decodeNoURL(response.body(), EncryptUtils.mbolsk)
                    val entity = JSONObject.parseObject(content, UnApplyBlastEntity::class.java)
                    saveAuthInfo(entity)
                    addLog("申请授权", "申请授权成功")
                }
            }

            override fun onError(response: Response<String>?) {
                loadDialog?.dismiss()
                addLog("申请授权", "申请授权失败")
                Toll.toll("提交失败")
            }

            override fun onFinish() {
                OkGoApi.api.setBaseUrl(AppConstant.baseUrl, application)
            }
        })
    }


    private fun saveAuthInfo(entity: UnApplyBlastEntity) {
        Loog.e(JSONObject.toJSONString(entity))
        ObservableUtil.doNext(ObservableOnSubscribe {
            if (!TextUtils.equals("0", entity.cwxx)) {
                it.onNext(false)
            } else {
                AppContext.appContext.saveAuthBlast(entity)
                if (entity.lgs != null && entity.lgs.lg != null && entity.lgs.lg.isNotEmpty()) {
                    DBHelper.queryLeiGuanEntity(object :
                        ObservableUtil.Companion.OnNextCallback<List<LeiGuanEntity>>() {
                        override fun onNext(t: List<LeiGuanEntity>) {
                            entity.lgs.lg.forEach { lg ->
                                t.forEach { lge ->
                                    if (TextUtils.equals(lge.UID, lg.uid)) {
                                        lge.password = lg.gzm
                                    }
                                    //测试用
                                    if (AppConstant.isTest) {
                                        lge.password = "00000000"
                                    }
                                }
                            }
                            DBHelper.updateLeiGuan(object :
                                ObservableUtil.Companion.OnNextCallback<Boolean>() {
                                override fun onNext(t: Boolean) {
                                    it.onNext(true)
                                }
                            }, *t.toTypedArray())
                        }
                    })
                }
            }
        }, object : ObservableUtil.Companion.OnNextCallback<Boolean>() {
            override fun onNext(t: Boolean) {
                loadDialog?.dismiss()
                if (!t) {
                    Toll.toll(DzlgErrorUtils.downloadError(entity.cwxx))
                } else {
                    val mRefreshDataEvent = RefreshDataEvent()
                    mRefreshDataEvent.isRefresh = true
                    LifecycleManager.manager.refreshLiveData(mRefreshDataEvent)
                    showAuthSuccessDialog()
                }
            }
        })
    }

    private fun showAuthSuccessDialog() {
        TipPop.showSure(this, "授权成功！", "确定", Action {
            finish()
        })
    }

    /**
     * 获取网络合同
     */
    private fun setNetHTView(buydept: String) {
        if (NetWorkUtils.isNetWorkAvailable(this)) {
            ManagerHttpUtil.getHtInfo(buydept,
                object : SerialHttpCallback<ContractInfoEntity>("List") {
                    override fun loadDataSuccess(datas: ArrayList<ContractInfoEntity>) {
                        if (datas.isNotEmpty()) {
                            onlineAuthHtCode.setText(datas[0].contractid)
                            onlineAuthXmCode.setText(datas[0].projectnumber)
                            onlineAuthHtName.setText(datas[0].contractname)
                            porjectName = datas[0].projectname
                            saveContractData(datas)
                        } else {
                            getDbContractData()
                        }
                    }

                    override fun loadDataFailed(e: Throwable) {
                        getDbContractData()
                    }
                })
        } else {
            getDbContractData()
        }
    }

    /**
     * 保存合同信息
     */
    private fun saveContractData(datas: ArrayList<ContractInfoEntity>) {
        DBHelper.setNewContract(object : ObservableUtil.Companion.OnNextCallback<Boolean>() {
            override fun onNext(t: Boolean) {
                setSelectContractData(datas)
            }
        }, *datas.toTypedArray())
    }

    /**
     * 获取本地合同信息
     */
    private fun getDbContractData() {
        DBHelper.queryContract(object :
            ObservableUtil.Companion.OnNextCallback<List<ContractInfoEntity>>() {
            override fun onNext(t: List<ContractInfoEntity>) {
                if (t.isNotEmpty()) {
                    setSelectContractData(t)
                }
            }
        })
    }


    /**
     * 设置选择项
     */
    private fun setSelectContractData(data: List<ContractInfoEntity>) {
        val hts = arrayListOf<String>()
        val xms = arrayListOf<String>()
        data.forEach {
            hts.add(it.contractid)
            xms.add(it.projectnumber)
        }

        onlineAuthHtCode.show(hts, AdapterView.OnItemClickListener { parent, view, position, id ->

        })

        onlineAuthXmCode.show(
            hts,
            AdapterView.OnItemClickListener { parent, view, position, id ->
                porjectName = data[position].projectname
            })

    }


    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        KeyBoardUtil.hideSoftInput(onlineAuthHtCode)
        KeyBoardUtil.hideSoftInput(onlineAuthXmCode)
        KeyBoardUtil.hideSoftInput(onlineAuthHtName)
    }

    override fun onDestroy() {
        super.onDestroy()
        keyEtViews.clear()
    }


    fun addLog(action: String, remark: String) {
        LogEntity.addLog(
            action,
            "",
            "未授权列表",
            ViewModelQuick.get(this, ShowDelayDataPresenter::class.java).getTotal(),
            0.0,
            0.0,
            "",
            0,
            0,
            "",
            remark
        )
    }
}





